﻿using System;
using System.Threading.Tasks;
using K9Nano.Caching;
using K9Nano.Dependency;

namespace K9Nano.MultiTenancy
{
    public class DefaultTenantCache : ITenantCache, ISingletonDependency
    {
        protected readonly ITypedCache<TenantInfo> Cache;

        public DefaultTenantCache(ITypedCache<TenantInfo> cache)
        {
            // !!!不通过EF直接读取数据库
            Cache = cache;
        }

        public virtual string Get(Guid id)
        {
            return Cache.Get(id.ToString())?.TenancyName;
        }

        public virtual Guid Get(string name)
        {
            return Cache.Get(name)?.Id ?? Guid.Empty;
        }

        public virtual void Set(TenantInfo tenant)
        {
            Cache.Put(tenant.TenancyName, tenant);
            Cache.Put(tenant.Id.ToString(), tenant);
        }

        public virtual void Delete(TenantInfo tenant)
        {
            Cache.Remove(tenant.Id.ToString());
            Cache.Remove(tenant.TenancyName);
        }
    }
}